<template>
	<view class="location-select-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content" :style="{ height: navBarHeight + 'px' }">
				<view class="nav-left" @click="goBack">
					<u-icon name="arrow-left" size="20" color="#333"></u-icon>
				</view>
				<text class="nav-title">选择位置</text>
				<view class="nav-right"></view>
			</view>
		</view>
		
		<!-- 搜索框 -->
		<view class="search-section">
			<view class="search-box">
				<u-icon name="search" size="16" color="#999"></u-icon>
				<input 
					v-model="searchKeyword" 
					placeholder="搜索地点、商圈、小区" 
					class="search-input"
					@input="onSearchInput"
					@confirm="searchLocation"
				/>
				<view v-if="searchKeyword" @click="clearSearch" class="clear-btn">
					<u-icon name="close" size="14" color="#999"></u-icon>
				</view>
			</view>
		</view>
		
		<!-- 当前位置 -->
		<view class="current-location-section">
			<view class="section-title">
				<u-icon name="map" size="16" color="#007AFF"></u-icon>
				<text class="title-text">当前位置</text>
				<view class="refresh-btn" @click="refreshLocation">
					<u-icon name="reload" size="14" color="#007AFF"></u-icon>
					<text class="refresh-text">刷新</text>
				</view>
			</view>
			
			<view v-if="currentLocation" class="location-item current" @click="selectCurrentLocation">
				<view class="location-info">
					<text class="location-name">{{ currentLocation.name || '当前位置' }}</text>
					<text class="location-address">{{ currentLocation.address }}</text>
				</view>
				<u-icon name="checkmark" size="16" color="#007AFF" v-if="isCurrentSelected"></u-icon>
			</view>
			
			<view v-else class="loading-location">
				<text class="loading-text">正在获取当前位置...</text>
			</view>
		</view>
		
		<!-- 搜索结果或历史位置 -->
		<view class="locations-section">
			<view v-if="searchResults.length > 0" class="search-results">
				<view class="section-title">
					<text class="title-text">搜索结果</text>
				</view>
				<view 
					v-for="(location, index) in searchResults" 
					:key="index"
					@click="selectLocation(location)"
					class="location-item"
				>
					<view class="location-info">
						<text class="location-name">{{ location.name }}</text>
						<text class="location-address">{{ location.address }}</text>
					</view>
					<text class="location-distance">{{ location.distanceText }}</text>
				</view>
			</view>
			
			<view v-else-if="!searchKeyword" class="history-locations">
				<view class="section-title">
					<text class="title-text">历史位置</text>
					<view class="clear-history" @click="clearHistory">
						<text class="clear-text">清空</text>
					</view>
				</view>
				
				<view v-if="historyLocations.length > 0">
					<view 
						v-for="(location, index) in historyLocations" 
						:key="index"
						@click="selectLocation(location)"
						class="location-item"
					>
						<view class="location-info">
							<text class="location-name">{{ location.name }}</text>
							<text class="location-address">{{ location.address }}</text>
						</view>
						<u-icon name="clock" size="14" color="#999"></u-icon>
					</view>
				</view>
				
				<view v-else class="empty-history">
					<text class="empty-text">暂无历史位置</text>
				</view>
			</view>
			
			<view v-else-if="searchKeyword && searchResults.length === 0" class="no-results">
				<text class="no-results-text">未找到相关位置</text>
			</view>
		</view>
		
		<!-- 底部按钮 -->
		<view class="bottom-actions">
			<button @click="openMapSelector" class="map-btn">
				<u-icon name="map" size="16" color="#007AFF"></u-icon>
				<text class="btn-text">在地图上选择</text>
			</button>
		</view>
	</view>
</template>

<script>
import wzLocation from '../../utils/wz_location.js'

export default {
	data() {
		return {
			statusBarHeight: 0,
			navBarHeight: 44,
			searchKeyword: '',
			currentLocation: null,
			searchResults: [],
			historyLocations: [],
			selectedLocation: null,
			isCurrentSelected: false,
			searchTimer: null
		}
	},
	
	async onLoad() {
		this.initNavbar()
		await this.getCurrentLocation()
		this.loadHistoryLocations()
	},
	
	methods: {
		// 初始化导航栏
		initNavbar() {
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight || 0
			
			// #ifdef MP-WEIXIN
			const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.navBarHeight = (menuButtonInfo.top - this.statusBarHeight) * 2 + menuButtonInfo.height
			// #endif
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 获取当前位置
		async getCurrentLocation() {
			try {
				this.currentLocation = await wzLocation.getCurrentLocation()
				console.log('当前位置:', this.currentLocation)
			} catch (error) {
				console.error('获取当前位置失败:', error)
			}
		},
		
		// 刷新当前位置
		async refreshLocation() {
			uni.showLoading({
				title: '获取位置中...'
			})
			
			try {
				this.currentLocation = await wzLocation.getCurrentLocation()
				uni.hideLoading()
				uni.showToast({
					title: '位置更新成功',
					icon: 'success'
				})
			} catch (error) {
				uni.hideLoading()
				uni.showToast({
					title: '位置更新失败',
					icon: 'none'
				})
			}
		},
		
		// 搜索输入
		onSearchInput() {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
			}
			
			this.searchTimer = setTimeout(() => {
				if (this.searchKeyword.trim()) {
					this.searchLocation()
				} else {
					this.searchResults = []
				}
			}, 500)
		},
		
		// 搜索位置
		async searchLocation() {
			if (!this.searchKeyword.trim()) return
			
			try {
				uni.showLoading({
					title: '搜索中...'
				})
				
				const results = await wzLocation.searchPOI(this.searchKeyword)
				
				// 计算距离并格式化结果
				this.searchResults = results.map(poi => {
					let distanceText = ''
					if (this.currentLocation && poi.latitude && poi.longitude) {
						const distance = wzLocation.calculateDistance(
							this.currentLocation,
							{ latitude: poi.latitude, longitude: poi.longitude }
						)
						distanceText = wzLocation.formatDistance(distance)
					}
					
					return {
						id: poi.id,
						name: poi.name,
						address: poi.address,
						latitude: poi.latitude,
						longitude: poi.longitude,
						distanceText: distanceText
					}
				})
				
				uni.hideLoading()
			} catch (error) {
				uni.hideLoading()
				console.error('搜索失败:', error)
				uni.showToast({
					title: '搜索失败',
					icon: 'none'
				})
			}
		},
		
		// 清空搜索
		clearSearch() {
			this.searchKeyword = ''
			this.searchResults = []
		},
		
		// 选择当前位置
		selectCurrentLocation() {
			if (this.currentLocation) {
				this.selectedLocation = this.currentLocation
				this.isCurrentSelected = true
				this.confirmSelection()
			}
		},
		
		// 选择位置
		selectLocation(location) {
			this.selectedLocation = location
			this.isCurrentSelected = false
			
			// 保存到历史记录
			this.saveToHistory(location)
			
			this.confirmSelection()
		},
		
		// 确认选择
		confirmSelection() {
			if (this.selectedLocation) {
				// 通过事件总线或页面参数传递选择的位置
				uni.$emit('locationSelected', this.selectedLocation)
				
				uni.showToast({
					title: '位置选择成功',
					icon: 'success'
				})
				
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			}
		},
		
		// 打开地图选择器
		async openMapSelector() {
			try {
				const location = await wzLocation.chooseLocation()
				this.selectLocation(location)
			} catch (error) {
				console.error('地图选择失败:', error)
			}
		},
		
		// 加载历史位置
		loadHistoryLocations() {
			try {
				const history = uni.getStorageSync('location_history') || []
				this.historyLocations = history
			} catch (error) {
				console.error('加载历史位置失败:', error)
			}
		},
		
		// 保存到历史记录
		saveToHistory(location) {
			try {
				let history = uni.getStorageSync('location_history') || []
				
				// 移除重复项
				history = history.filter(item => 
					item.latitude !== location.latitude || item.longitude !== location.longitude
				)
				
				// 添加到开头
				history.unshift(location)
				
				// 限制历史记录数量
				if (history.length > 10) {
					history = history.slice(0, 10)
				}
				
				uni.setStorageSync('location_history', history)
				this.historyLocations = history
			} catch (error) {
				console.error('保存历史位置失败:', error)
			}
		},
		
		// 清空历史记录
		clearHistory() {
			uni.showModal({
				title: '提示',
				content: '确定要清空历史位置吗？',
				success: (res) => {
					if (res.confirm) {
						uni.removeStorageSync('location_history')
						this.historyLocations = []
						uni.showToast({
							title: '已清空',
							icon: 'success'
						})
					}
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.location-select-container {
	background-color: #f8f8f8;
	min-height: 100vh;
}

.custom-navbar {
	background-color: #fff;
	border-bottom: 1px solid #eee;
	
	.navbar-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 15px;
		
		.nav-left, .nav-right {
			width: 40px;
			height: 40px;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.nav-title {
			font-size: 18px;
			font-weight: 600;
			color: #333;
		}
	}
}

.search-section {
	padding: 15px;
	background-color: #fff;
	border-bottom: 1px solid #eee;
	
	.search-box {
		display: flex;
		align-items: center;
		background-color: #f5f5f5;
		border-radius: 20px;
		padding: 8px 15px;
		
		.search-input {
			flex: 1;
			margin-left: 8px;
			font-size: 14px;
			color: #333;
		}
		
		.clear-btn {
			padding: 4px;
		}
	}
}

.current-location-section {
	background-color: #fff;
	margin-bottom: 10px;
}

.locations-section {
	background-color: #fff;
}

.section-title {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px;
	border-bottom: 1px solid #f0f0f0;
	
	.title-text {
		font-size: 14px;
		color: #666;
		margin-left: 5px;
	}
	
	.refresh-btn {
		display: flex;
		align-items: center;
		
		.refresh-text {
			font-size: 12px;
			color: #007AFF;
			margin-left: 3px;
		}
	}
	
	.clear-history {
		.clear-text {
			font-size: 12px;
			color: #999;
		}
	}
}

.location-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px;
	border-bottom: 1px solid #f0f0f0;
	
	&.current {
		background-color: #f8f9ff;
	}
	
	.location-info {
		flex: 1;
		
		.location-name {
			display: block;
			font-size: 16px;
			color: #333;
			margin-bottom: 4px;
		}
		
		.location-address {
			display: block;
			font-size: 12px;
			color: #999;
		}
	}
	
	.location-distance {
		font-size: 12px;
		color: #666;
	}
}

.loading-location {
	padding: 20px 15px;
	text-align: center;
	
	.loading-text {
		font-size: 14px;
		color: #999;
	}
}

.empty-history {
	padding: 30px 15px;
	text-align: center;
	
	.empty-text {
		font-size: 14px;
		color: #999;
	}
}

.no-results {
	padding: 30px 15px;
	text-align: center;
	
	.no-results-text {
		font-size: 14px;
		color: #999;
	}
}

.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 15px;
	background-color: #fff;
	border-top: 1px solid #eee;
	
	.map-btn {
		width: 100%;
		height: 44px;
		background-color: #007AFF;
		color: #fff;
		border: none;
		border-radius: 22px;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.btn-text {
			margin-left: 5px;
			font-size: 16px;
		}
	}
}
</style>